package com.example.demo;

import org.quartz.JobDataMap;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.quartz.CronTriggerFactoryBean;
import org.springframework.scheduling.quartz.JobDetailFactoryBean;
import org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;

@Configuration
public class QuartzConfig {
    /**
     * 执行任务的bean(普通的类的方法)
     * @return
     */
    @Bean
    MethodInvokingJobDetailFactoryBean jobDetailFactoryBean() {
        MethodInvokingJobDetailFactoryBean bean = new MethodInvokingJobDetailFactoryBean();
        bean.setTargetBeanName("myFirstJob");
        bean.setTargetMethod("foo");
        return bean;
    }
    /**
     * 执行任务的bean(继承了QuartzJobBean的类的方法)
     * @return
     */
    @Bean
    JobDetailFactoryBean jobDetailFactoryBean2() {
        JobDetailFactoryBean bean = new JobDetailFactoryBean();
        bean.setJobClass(MySecondJob.class);
        JobDataMap map = new JobDataMap();
        map.put("name","accp");
        bean.setJobDataMap(map);
        bean.setDurability(true);
        return bean;
    }
    /**
     * 定义任务执行周期的bean
     * @return
     */
    @Bean
    CronTriggerFactoryBean cronTriggerFactoryBean() {
        CronTriggerFactoryBean bean = new CronTriggerFactoryBean();
//        bean.setJobDetail(jobDetailFactoryBean().getObject());
        bean.setJobDetail(jobDetailFactoryBean2().getObject());
        bean.setCronExpression("0/3 * * * * ?");
        return bean;
    }

    /**
     * 执行bean,复制把任务和周期组合到一起执行
     * @return
     */
    @Bean
    SchedulerFactoryBean schedulerFactoryBean() {
        SchedulerFactoryBean schedulerFactoryBean = new SchedulerFactoryBean();
        schedulerFactoryBean.setTriggers(cronTriggerFactoryBean().getObject());
        return schedulerFactoryBean;
    }
}
